import axios from 'axios'
// import router from '@/router'
import consts from '@/service/consts'
// import store from '@/store'

const service = axios.create({
  baseURL: consts.baseUrl + (consts.port === 80 ? '' : `:${consts.port}`), // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  timeout: 20 * 1000 // request timeout
})
// 请求拦截器
service.interceptors.request.use(config => {
  // 登录判断
  const token = localStorage.getItem(consts.token)
  if (token) {
    config.headers.token = token
  }

  return config
}, error => {
  console.log('请求拦截器 error=>', error)
  return Promise.error(error)
})
// 响应拦截器
service.interceptors.response.use(response => {
  const res = response.data
  // if (res.code === 2) {
  //   store.dispatch('removerUser')
  //   // 重新登录
  //   router.push('/user/login')
  // } else {
  if (res.code === 200) {
    return res
  } else {
    return Promise.reject(res)
  }
  // }
}, error => {
  console.log('响应拦截器 error=>', error)
  return Promise.reject(error)
})
export default service
